package com.algorithm;

/**
 * Created by houjinxin on 16/5/5.
 */
public class PrintDigits {

    public static void main(String[] args) {
        int i = 76325;
        double d = 1234.95;
//        System.out.print((int)d);
        printDoubleOut(d, 2);
//        printIntOut(i);

    }

    /**
     * n % 10 = n - 10 * (n / 10)
     * 取模运算因CPU耗时较高,故换做一个性能高的算法
     *
     * @param n
     */
    public static void printIntOut(int n) {
        if (n >= 10) {
            printIntOut(n / 10);
        }
//        printDigits(n % 10);
        printDigits(n - 10 * (n / 10));
    }

    public static void printDoubleOut(double d, int radix) {
        int integer = (int) d; //取整
        double decimal = round(d % 1, radix); //取小数
        if (integer >= 10) {
            printDoubleOut(integer / 10, radix);
        }
        if (decimal < 1 && decimal > 0) { //小数部分的处理
            printDoubleOut(decimal * 10, radix);
        } //d在[0,9]之间
        printDigits(integer - 10 * (integer / 10));
        System.out.print(".");
    }

    public static void printDigits(int n) {
        System.out.print(n);
    }

    /**
     * 四舍五入
     *
     * @param original
     * @param radix
     * @return
     */
    public static double round(double original, int radix) {
        double factor = Math.pow(10.0, radix); //这里一定是10.0 否则会按照整形计算
        return Math.round(original * factor) / factor;
    }
}
